"""
RS232接口使用示例

演示如何使用RS232接口与雷达设备通信
"""

import sys
import time
import json
from pathlib import Path

# 添加项目路径
sys.path.insert(0, str(Path(__file__).parent.parent))

from radar_client import RadarClient
from radar_client.config import RadarConfig


def basic_rs232_example():
    """RS232基础使用示例"""
    print("=== RS232基础使用示例 ===")

    # 创建雷达客户端
    client = RadarClient()

    try:
        # 连接RS232接口
        print("正在连接RS232接口...")
        client.connect_rs232({
            'port': 'COM1',
            'baud_rate': 115200,
            'data_bits': 8,
            'stop_bits': 1,
            'parity': 'none',
            'flow_control': 'none'
        })

        # 获取连接信息
        connection_info = client.get_connection_info()
        print(f"连接信息: {json.dumps(connection_info, indent=2, ensure_ascii=False)}")

        # 获取雷达状态
        print("\n获取雷达状态...")
        status = client.get_status()
        print(f"雷达状态: {status.to_dict()}")

        # 启动扫描
        print("\n启动雷达扫描...")
        result = client.start_scan()
        print(f"启动扫描结果: {result}")

        # 获取目标数据
        print("\n获取目标数据...")
        targets = client.get_targets()
        print(f"发现 {len(targets)} 个目标:")
        for i, target in enumerate(targets):
            print(f"  目标 {i+1}: {target.to_dict()}")

        # 停止扫描
        print("\n停止雷达扫描...")
        result = client.stop_scan()
        print(f"停止扫描结果: {result}")

    except Exception as e:
        print(f"错误: {e}")

    finally:
        # 断开连接
        client.disconnect()
        print("连接已断开")


def baud_rate_example():
    """不同波特率测试示例"""
    print("\n=== 不同波特率测试示例 ===")

    baud_rates = [9600, 19200, 38400, 115200]

    for baud_rate in baud_rates:
        print(f"\n测试波特率: {baud_rate}")

        client = RadarClient()

        try:
            # 连接RS232接口
            client.connect_rs232({
                'port': 'COM1',
                'baud_rate': baud_rate,
                'timeout': 2000
            })

            # 获取状态
            status = client.get_status()
            print(f"  状态获取成功: 温度={status.temperature:.1f}°C")

            # 断开连接
            client.disconnect()

        except Exception as e:
            print(f"  波特率 {baud_rate} 测试失败: {e}")


def parity_config_example():
    """校验位配置示例"""
    print("\n=== 校验位配置示例 ===")

    parity_configs = [
        {'parity': 'none', 'name': '无校验'},
        {'parity': 'odd', 'name': '奇校验'},
        {'parity': 'even', 'name': '偶校验'}
    ]

    for config in parity_configs:
        print(f"\n测试 {config['name']}:")

        client = RadarClient()

        try:
            # 连接RS232接口
            client.connect_rs232({
                'port': 'COM1',
                'baud_rate': 115200,
                'parity': config['parity']
            })

            # 获取状态
            status = client.get_status()
            print(f"  连接成功: {config['name']}")

            # 断开连接
            client.disconnect()

        except Exception as e:
            print(f"  {config['name']} 失败: {e}")


def flow_control_example():
    """流控制配置示例"""
    print("\n=== 流控制配置示例 ===")

    flow_configs = [
        {'flow_control': 'none', 'name': '无流控制'},
        {'flow_control': 'hardware', 'name': '硬件流控制'},
        {'flow_control': 'software', 'name': '软件流控制'}
    ]

    for config in flow_configs:
        print(f"\n测试 {config['name']}:")

        client = RadarClient()

        try:
            # 连接RS232接口
            client.connect_rs232({
                'port': 'COM1',
                'baud_rate': 115200,
                'flow_control': config['flow_control']
            })

            # 获取状态
            status = client.get_status()
            print(f"  连接成功: {config['name']}")

            # 断开连接
            client.disconnect()

        except Exception as e:
            print(f"  {config['name']} 失败: {e}")


def port_scan_example():
    """串口扫描示例"""
    print("\n=== 串口扫描示例 ===")

    # 常见串口名称
    if sys.platform == 'win32':
        ports = [f'COM{i}' for i in range(1, 17)]
    else:
        ports = ['/dev/ttyUSB0', '/dev/ttyUSB1', '/dev/ttyACM0', '/dev/ttyACM1']

    print("扫描可用串口...")

    for port in ports:
        print(f"  测试端口: {port}")

        client = RadarClient()

        try:
            # 快速连接测试
            client.connect_rs232({
                'port': port,
                'timeout': 500
            })

            # 获取状态
            status = client.get_status()
            print(f"    ✓ 找到设备: {port}")
            print(f"      温度: {status.temperature:.1f}°C")

            # 断开连接
            client.disconnect()

        except Exception as e:
            print(f"    ✗ {port}: {str(e)[:50]}")


def continuous_monitoring_example():
    """连续监控示例"""
    print("\n=== 连续监控示例 ===")

    def status_callback(status):
        print(f"[状态] 温度: {status.temperature:.1f}°C, 电压: {status.voltage:.2f}V")

    def target_callback(targets):
        if targets:
            print(f"[目标] 检测到 {len(targets)} 个目标")
            for target in targets:
                print(f"  ID:{target.target_id} 距离:{target.range_val:.1f}m 速度:{target.velocity:.1f}m/s")

    def error_callback(error):
        print(f"[错误] {error}")

    client = RadarClient()

    try:
        # 设置回调函数
        client.set_status_callback(status_callback)
        client.set_target_callback(target_callback)
        client.set_error_callback(error_callback)

        # 连接RS232接口
        client.connect_rs232({
            'port': 'COM1',
            'baud_rate': 115200
        })

        # 启动扫描
        client.start_scan()
        print("开始监控... (10秒)")

        # 监控10秒
        time.sleep(10)

        # 停止扫描
        client.stop_scan()
        print("监控结束")

    except Exception as e:
        print(f"错误: {e}")

    finally:
        client.disconnect()


def configuration_file_example():
    """配置文件使用示例"""
    print("\n=== 配置文件使用示例 ===")

    # 创建RS232配置文件
    rs232_config = {
        "rs232": {
            "port": "COM1",
            "baud_rate": 115200,
            "data_bits": 8,
            "stop_bits": 1,
            "parity": "none",
            "flow_control": "none",
            "timeout": 1000,
            "response_delay": 50,
            "max_retries": 3
        },
        "general": {
            "enable_logging": True,
            "log_level": "INFO",
            "auto_reconnect": True,
            "reconnect_interval": 3000,
            "data_callback_enabled": True,
            "command_timeout": 2000
        }
    }

    config_file = Path(__file__).parent / "rs232_config.json"

    try:
        import json
        with open(config_file, 'w', encoding='utf-8') as f:
            json.dump(rs232_config, f, indent=2, ensure_ascii=False)

        print(f"配置文件已创建: {config_file}")

        # 使用配置文件
        client = RadarClient(config_file=str(config_file))

        # 连接
        client.connect_rs232()

        # 获取状态
        status = client.get_status()
        print(f"雷达状态: {status.to_dict()}")

        # 获取目标数据
        targets = client.get_targets()
        print(f"检测到 {len(targets)} 个目标")

    except Exception as e:
        print(f"错误: {e}")

    finally:
        client.disconnect()


if __name__ == "__main__":
    """运行所有示例"""
    print("RS232雷达客户端示例程序")
    print("=" * 50)

    # 运行示例
    basic_rs232_example()
    baud_rate_example()
    parity_config_example()
    flow_control_example()
    port_scan_example()
    continuous_monitoring_example()
    configuration_file_example()

    print("\n" + "=" * 50)
    print("示例程序运行完成")